<template>
  <div class="building-container">
    <!-- 搜索区域 -->
    <div class="search-container">
      <div class="search-label">企业名称：</div>

      <el-input
        v-model.trim="params.name"
        clearable
        placeholder="请输入内容"
        class="search-main"
        @clear="doSearch"
      />
      <el-button type="primary" @click="doSearch">查询</el-button>
    </div>

    <div class="create-container">
      <auth-button btn-string="park:enterprise:add_edit">
      <el-button type="primary" @click="$router.push('/exterpriseAdd')"
        >添加企业</el-button
      >
      </auth-button>
    </div>

    <!-- 表格区域 -->
    <div class="table">
      <el-table
        style="width: 100%"
        :data="exterpriseList"
        @expand-change="expandHandle"
      >
        <el-table-column type="index" label="序号" />
        <el-table-column label="企业名称" width="320" prop="name" />
        <el-table-column label="联系人" prop="contact" />
        <el-table-column label="联系电话" prop="contactNumber" />
        <el-table-column label="操作">
          <template #default="scope">
            <el-button size="mini" type="text" @click="addRent(scope.row)"
              >添加合同</el-button
            >

            <el-button
              size="mini"
              type="text"
              @click="handler('look', scope.row)"
              >查看</el-button
            >

            <el-button
              size="mini"
              type="text"
              :disabled="scope.row.existContractFlag? true : false"
              @click="handler('edit', scope.row)"
              >编辑</el-button
            >

            <el-button
              size="mini"
              type="text"
              :disabled="scope.row.existContractFlag? true : false"
              @click="handler('del', scope.row)"
              >删除</el-button
            >
          </template>
        </el-table-column>

        <el-table-column type="expand">
          <template #default="scope">
            <el-table :data="rentList[scope.row.id]">
              <el-table-column label="租赁楼宇" prop="buildingName" />
              <el-table-column label="租赁起始时间">
                <template #default="scope">
                  {{ scope.row.startTime }} 至 {{ scope.row.endTime }}
                </template>
              </el-table-column>
              <el-table-column label="合同状态">
                <template #default="scope">
                  <el-tag
                    :type="
                      mapList[scope.row.status] === '待生效'
                        ? 'primary'
                        : 'success'
                    "
                    disable-transitions
                    >{{ mapList[scope.row.status] }}</el-tag
                  >
                </template>
              </el-table-column>
              <el-table-column label="操作">
                <template #default="scope">
                  <el-button
                    size="mini"
                    type="text"
                    :disabled="scope.row.renewFlag !== 1"
                    @click="getCard(scope.row)"
                    >续租</el-button
                  >
                  <el-button
                    size="mini"
                    type="text"
                    :disabled="scope.row.exitFlag !== 1"
                    @click="outRent(scope.row.id)"
                    >退租</el-button
                  >

                  <el-button
                    size="mini"
                    type="text"
                    :disabled="scope.row.status !== 3"
                    @click="delRent(scope.row.id)"
                    >删除</el-button
                  >
                </template>
              </el-table-column>
            </el-table>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
      @size-change="handleSizeChange"
      @current-change="pageChange"
      :current-page="params.page"
      :page-sizes="[10, 20, 30, 40]"
      :page-size="params.pageSize"
      layout="total,  prev, pager, next, sizes, jumper"
      :total="total"
    >
    </el-pagination>
    </div>

    <el-dialog
      :title="extend.name ? '续租合同' : '添加合同'"
      :visible="rentDialogVisible"
      width="580px"
      @close="closeDialog"
    >
      <!-- 表单区域 -->
      <div class="form-container">
        <el-form
          ref="addForm"
          :model="rentForm"
          :rules="rentRules"
          label-position="top"
        >
          <el-form-item label="租赁楼宇" prop="buildingId">
            <el-select
              :value="extend.name || rentForm.buildingId"
              @change="handleSelectChange"
              placeholder="请选择"
              :disabled="extend.name ? true : false"
            >
              <!-- <el-select v-model="rentForm.buildingId" placeholder="请选择"> -->
              <el-option
                v-for="item in buildList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="租赁起止日期" prop="rentTime">
            <el-date-picker
              v-if="!extend.time"
              v-model="rentForm.rentTime"
              type="daterange"
              range-separator=">"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="yyyy-MM-dd"
              :picker-options="pickerOptions"
            >
            </el-date-picker>
            <div v-else class="timeFlag">
              <el-date-picker
                v-model="rentForm.rentTime[0]"
                type="date"
                placeholder="开始日期"
                value-format="yyyy-MM-dd"
                :disabled="true"
              >
              </el-date-picker>
              <el-date-picker
                v-model="rentForm.rentTime[1]"
                value-format="yyyy-MM-dd"
                type="date"
                :picker-options="pickerOptionsAdd"
                placeholder="结束日期"
              >
              </el-date-picker>
            </div>
          </el-form-item>

          <el-form-item label="租赁合同" prop="contractId">
            <el-upload action="#" :http-request="uploadHandle">
              <el-button size="small" type="primary" plain
                >上传合同文件</el-button
              >

              <div slot="tip" class="el-upload__tip">
                支持扩展名：.doc .docx .pdf, 文件大小不超过5M
              </div>
            </el-upload>
          </el-form-item>
        </el-form>
      </div>

      <template #footer>
        <el-button size="mini" @click="closeDialog">取 消</el-button>

        <el-button size="mini" type="primary" @click="confirmAdd"
          >确 定</el-button
        >
      </template>
    </el-dialog>
  </div>
</template>
<script>
import {
  getEnterpriseListAPI,
  delExterpriseAPI,
  createRentAPI,
  uploadAPI,
  getRentListAPI,
  getRentBuildListAPI,
  outRentAPI,
  delRentAPI,
} from "@/api/park";
import { Message } from "element-ui";
export default {
  name: "Building",
  data() {
    return {
      addTime: "",
      extend: {
        name: "",
        time: "",
      },
      pickerOptions: {
        disabledDate(time) {
          const minDate = new Date();
          return time.getTime() < minDate.getTime();
        },
      },
      pickerOptionsAdd: {
        disabledDate: (time) => {
          const startDate = this.rentForm.rentTime[0];
          if (startDate) {
            const minDate = new Date(startDate);
            return time.getTime() < minDate.getTime();
          }
          return false;
        },
      },
      rentList: {},
      mapList: {
        0: "待生效",
        1: "生效中",
        2: "已到期",
        3: "已退租",
      },
      buildList: [],
      rentDialogVisible: false,
      exterpriseList: [],
      params: {
        page: 1,
        pageSize: 10,
        name: "",
      },
      total: 0,
      rentForm: {
        buildingId: null, // 楼宇id
        contractId: null, // 合同id
        contractUrl: "", // 合同Url
        enterpriseId: null, // 企业名称
        type: 0, // 合同类型
        rentTime: [], // 合同时间
      },
      rentRules: {
        buildingId: [
          { required: true, message: "请选择楼宇", trigger: "change" },
        ],
        rentTime: [
          { required: true, message: "请选择租赁日期", trigger: "change" },
        ],
        contractId: [{ required: true, message: "请上传合同文件" }],
      },
    };
  },
  async created() {
    this.getExterpriseList();
    const res = await getRentBuildListAPI();
    this.buildList = res.data;
  },
  methods: {
    getNextDay(time) {
      // 把输入的日期字符串转换为 Date 对象
      const currentDate = new Date(time);
      // 为当前日期加上一天的毫秒数
      currentDate.setDate(currentDate.getDate() + 1);
      // 获取年、月、日信息
      const year = currentDate.getFullYear();
      // 月份是从 0 开始计数的，所以要加 1，并且保证月份是两位数
      const month = String(currentDate.getMonth() + 1).padStart(2, "0");
      // 保证日期是两位数
      const day = String(currentDate.getDate()).padStart(2, "0");
      // 按照 YYYY-MM-DD 格式组合日期
      return `${year}-${month}-${day}`;
    },
    handleSelectChange(value) {
      this.rentForm.buildingId = value;
    },
    async delRent(id) {
      await delRentAPI(id);
      this.getExterpriseList();
    },
    outRent(rentId) {
      this.$confirm("确认退租吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          // 1. 调用接口
          await outRentAPI(rentId);
          // 2. 重新拉取列表
          this.getEnterpriseListAPI();

          this.$message({
            type: "success",
            message: "退租成功!",
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    async expandHandle(row, rows) {
      const isExpend = rows.find((item) => item.id === row.id);
      if (isExpend) {
        const res = await getRentListAPI(row.id);
        this.$set(this.rentList, row.id, res.data);
        console.log(this.rentList);
      }
    },
    async getExterpriseList() {
      const res = await getEnterpriseListAPI(this.params);
      this.exterpriseList = res.data.rows;
      this.total = res.data.total;
    },
    confirmAdd() {
      this.$refs.addForm.validate(async (valid) => {
        if (valid) {
          const { buildingId, contractId, contractUrl, enterpriseId, type } =
            this.rentForm;
          await createRentAPI({
            buildingId,
            contractId,
            contractUrl,
            enterpriseId,
            type,
            startTime: this.rentForm.rentTime[0],
            endTime: this.rentForm.rentTime[1],
          });
          // 更新列表
          this.getExterpriseList();
          // 关闭弹框
          this.rentDialogVisible = false;
          this.$refs.addForm.resetFields();
        }
      });
    },
    async uploadHandle(fileData) {
      console.log(fileData);

      // 1. 处理FormData
      const { file } = fileData;
      const formData = new FormData();
      formData.append("file", file);
      formData.append("type", "contract");
      // 2. 上传并赋值
      const res = await uploadAPI(formData);
      const { id, url } = res.data;
      this.rentForm.contractId = id;
      this.rentForm.contractUrl = url;
      // 单独校验表单
      this.$refs.addForm.validate("contractId");
      console.log(this.rentForm);
    },
    async handler(str, { id }) {
      if (str === "edit") {
        this.$router.push({
          path: "/exterpriseAdd",
          query: {
            id,
          },
        });
      } else if (str === "del") {
        await this.$confirm("确定删除该企业吗?");
        try {
          await delExterpriseAPI(id);
          Message.success("删除成功");
          this.getExterpriseList();
        } catch (err) {
          Message.error(err);
        }
      } else if (str === "look") {
        this.$router.push({
          path: "/exterpriseDetail",
          query: {
            id,
          },
        });
      }
    },
    async addRent(id) {
      this.rentForm.type = 0;
      this.$set(this.extend, "name", "");
      this.$set(this.extend, "time", "");
      this.rentDialogVisible = true;
      this.rentForm.enterpriseId = id.id;
      this.$refs.addForm.resetFields();
    },
    async getCard(row) {
      this.rentForm.type = 1;
      let list = this.rentList;
      for (let key in list) {
        if (list[key].includes(row)) {
          this.rentForm.enterpriseId = +key;
          break;
        }
      }
      this.rentForm.buildingId = row.buildingId;
      this.extend.name = row.buildingName;
      this.extend.time = row.endTime;
      this.rentForm.rentTime[0] = this.getNextDay(row.endTime);
      this.rentDialogVisible = true;
    },
    closeDialog() {
      this.rentDialogVisible = false;
    },
    doSearch() {
      this.params.page = 1;
      this.getExterpriseList();
    },
    pageChange(page) {
      this.params.page = page;
      this.getExterpriseList();
    },
    handleSizeChange(pageSize) {
      this.params.pageSize = pageSize;
      this.getExterpriseList();
    }
  },
};
</script>

<style lang="scss" scoped>
.timeFlag {
  display: flex;
}
.department-container {
  padding: 10px;
}

.search-container {
  display: flex;
  align-items: center;
  border-bottom: 1px solid rgb(237, 237, 237, 0.9);
  padding-bottom: 20px;

  .search-label {
    width: 100px;
  }

  .search-main {
    width: 220px;
    margin-right: 10px;
  }
}
.create-container {
  margin: 10px 0px;
}
.page-container {
  padding: 4px 0px;
  text-align: right;
}
.form-container {
  padding: 0px 80px;
}
.create-container {
  margin-bottom: 20px;
  margin-top: 20px;
}
::v-deep .el-pagination {
  margin-top: 30px;
}
::v-deep .el-table__header-wrapper th {
  background-color: #f4f6f8;
}
::v-deep .el-pagination {
  margin-top: 30px;
  text-align: right;
}
</style>
